// pages/details/details.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    nn:0,
    imgheights:[],
    circular: true,
    //是否显示画板指示点  
    indicatorDots: true,
    //选中点的颜色  
    indicatorcolor: "#000",
    //是否竖直  
    vertical: false,
    //是否自动切换  
    autoplay: true,
    //自动切换的间隔
    interval: 2500,
    //滑动动画时长毫秒  
    duration: 100,
    //所有图片的高度  
    imgheights: [],
    //图片宽度 
    imgwidth: 750,
    //默认  
    current: 0,
    // 单价
    price: '',
    // 总价
    totalPrice: '',
    // 商品数量
    shopNum: 1,
    // 产品信息
    product: {
    },
    // sku存储
    sku: {
      sku: '',
      pic: '',
      price: '',
    },
    // 选择型号
    select: false,
    // 加入购物车
    // addCart: false,
    production: [{
        img: "https://img11.360buyimg.com/ddimg/jfs/t1/140394/4/9410/24358/5f6ecf5bE5bcdedce/63f821895c66b076.jpg"
      },
      {
        img: "https://img14.360buyimg.com/ddimg/jfs/t1/139172/34/9352/24163/5f6ecf08Ec6a3944f/4f9ec246c062dbf5.jpg"
      },
      {
        img: "https://img14.360buyimg.com/ddimg/jfs/t1/129334/30/13490/209192/5f6e2c4cE38f6bb29/fde8220acd0d99d2.png"
      },
      {
        img: "https://img11.360buyimg.com/ddimg/jfs/t1/140394/4/9410/24358/5f6ecf5bE5bcdedce/63f821895c66b076.jpg"
      }
    ],
    num: "",
    money: 20,
    oldmoney: 20.99,
    // 选中
    selectd: 0,
    selectdTwo: 0,
    freight: 10,
    odortype: "郫县豆瓣味",
    alcoholstrength: "80%ml",
    material: "白酒，啤酒，葡萄酒",
    contents: "别看了，兑了水",
    packaging: "包装都比酒贵",
    hardback: "没有",
    addrs: "四川泸州具体的自己定位",
    jiuimg: "https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=1849427806,1639082937&fm=26&gp=0.jpg",
  },
  imageLoad: function (e) {//获取图片真实宽度  
    var imgwidth = e.detail.width,
      imgheight = e.detail.height,
      //宽高比  
      ratio = imgwidth / imgheight;
    //计算的高度值  
    var viewHeight = 750 / ratio;
    var imgheight = viewHeight;
    var imgheights = this.data.imgheights;
    //把每一张图片的对应的高度记录到数组里  
    imgheights[e.target.dataset.id] = imgheight;
    this.setData({
      imgheights: imgheights
    })
  },

  // 产品数量增加
  changeNum(e) {
    let shopNum = this.data.shopNum
    let price = this.data.price
    let opaer = e.currentTarget.dataset.opaer

    if (opaer == 'add'){
      shopNum++
    }else if (opaer == 'reduce') {
      shopNum--
      if (shopNum < 1) {
        shopNum = 1
      }
    }
    let totalPrice = price * shopNum
    totalPrice = totalPrice.toFixed(2)
    this.setData({
      shopNum,
      totalPrice
    })
  },
  // 选择型号
  selectModel (){
    let select = this.data.select
    select = true
    this.setData({
      select
    })
  },
  // 选中的项
  seleceHandle(e){
    let key = e.currentTarget.dataset.title;
    if (key == '香型'){
      key = 'sku'
      this.setData({
        selectd: e.currentTarget.dataset.index,
      })
    }else if (key == '净量'){
      key = "pic"
      this.setData({
        selectdTwo: e.currentTarget.dataset.index,
      })
    }
    let obj = this.data.sku
    obj[key] = e.currentTarget.dataset.pro
    if (obj.sku != "" & obj.pic != "" ){
        let price = ''
        let totalPrice = ''
        let shopType = `${obj.sku}+${obj.pic}`
        let pro = this.data.product.edition.SKU.filter(item => {
          if (item.title == shopType){
            return item
          }
        })
        price = pro[0].price
        obj.price = price
        totalPrice = price * this.data.shopNum
        totalPrice = totalPrice.toFixed(2)
        this.setData({
          totalPrice,
          price
        })
    }
    this.setData({
      sku: obj
    })
  },
  hideSku: function(e){
    this.setData({
      select: false
    })
  },
  stopPopo: function(e){
    return
  },
  purchase:function(){
    if (this.data.select == false){
      this.setData({
        select: true
      })
      return
    }
    let that = this
    let sku = that.data.sku
    wx.request({
      url: 'http://api_dev.wanxikeji.cn/api/shoppingCarAddModify',
      method: 'POST',
      data: {
        token: wx.getStorageSync('token'),
        good_id: that.data.product.good_id,
        num: this.data.shopNum,
        price: that.data.price,
        money: that.data.totalPrice,
        sku: JSON.stringify(sku)
      },
      success: res => {
        wx.request({//模拟购物车列表
          url: 'http://api_dev.wanxikeji.cn/api/shoppingCarList',
          method:'POST',
          data: {
              token: wx.getStorageSync("token"),
          },
          success: (res) => {
            let data = res.data.data.data
            let shopping_car_ids = data.map(item => {
              return item.shopping_car_id
            })
            let shopping_car_id = Math.max(...shopping_car_ids)
            shopping_car_ids = []
            shopping_car_ids.push(shopping_car_id)
            let address_id = ''
            wx.request({
              url: 'http://api_dev.wanxikeji.cn/api/userAddressList',
              method: 'POST',
              data: {
                token: wx.getStorageSync('token')
              },
              success: res => {
                address_id = res.data.data[0].address_id
                wx.request({
                  url: 'http://api_dev.wanxikeji.cn//api/generateOrder',
                  method: 'POST',
                  data: {
                    token: wx.getStorageSync('token'),
                    address_id: address_id,
                    money: this.data.totalPrice,
                    shopping_car_ids: shopping_car_ids
                  },
                  success: res => {
                    let bb = {
                      address_id:address_id,
                      shopping_car_ids:shopping_car_ids
                    }
                    wx.setStorageSync('bb', bb)
                    wx.navigateTo({
                        url: '/pages/orders/orders',
                    });
                  }
                })
              }
            })

          }
      })
      }
    })
    
  },
  // 类型选择
  bindMultiPickerChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      multiIndex: e.detail.value
    })
  },

  // 加入购物车
  addCart: function(){
    if (this.data.select == false){
      this.setData({
        select: true
      })
      return
    }
    let that = this
    let sku = that.data.sku
    wx.request({
      url: 'http://api_dev.wanxikeji.cn/api/shoppingCarAddModify',
      method: 'POST',
      data: {
        token: wx.getStorageSync('token'),
        good_id: that.data.product.good_id,
        num: this.data.shopNum,
        price: that.data.price,
        money: that.data.totalPrice,
        sku: JSON.stringify(sku)
      },
      success: res => {
        wx.request({
          url: 'http://api_dev.wanxikeji.cn/api/shoppingCarList',
          method: 'POST',
          data: {
            token: wx.getStorageSync('token'),
          },
          success:res=>{
            let nu = 0;
            res.data.data.data.forEach(v=>{
              if(v.good_id == that.data.product.good_id){
                nu++;
                return nu;
              }
            })
            wx.request({//模拟购物车列表
              url: 'http://api_dev.wanxikeji.cn/api/shoppingCarList',
              method:'POST',
              data: {
                  token: wx.getStorageSync("token"),
              },
              success: (res) => {
                  let a = [];
                  a = res.data.data.data;
                  let app = getApp()
                  app.scanCart(that)
                  //去重
                  var hash = [];
                  var ii = [];
                  a = a.reduce(function(x, y,index,arr) {
                      if(hash[y['sku']]){
                          ii.push(y.shopping_car_id);
                          wx.setStorageSync('ii', ii);
                          arr.forEach(item=>{
                              if(item.sku==y.sku){
                                  item.num++;
                              }
                          });
                          
                      }
                      hash[y['sku']] ? '' : hash[y['sku']] = true && x.push(y);
                      return x;
                  }, []);
                  wx.setStorageSync('cartLen', a.length);
                  console.log(wx.getStorageSync('cartLen'));
                  this.setData({
                    nn:wx.getStorageSync('cartLen')
                  })
              }
          })
          }
        });
        if (res.statusCode == 200 ){
          wx.switchTab({
            // url: '../cart/cart',
            success: function(e) {
              var page = getCurrentPages().pop()
              if (page == undefined || page == null) return;
              page.onLoad()
            }
          })
          this.hideSku();
        }
      }
    })
  },
  tocar: function () {
    wx.reLaunch({
      url: '/pages/cart/cart',
    })
  },
  bindRegionChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      region: e.detail.value
    })
  },

  // 获取详细数据
  getDetail(shopId){
    // 请求数据
    wx.request({
      url: 'http://api_dev.wanxikeji.cn/api/goodInfo',
      data: {
        token: wx.getStorageSync('token'),
        good_id: String(shopId)
      },
      success: res => {
        // console.log(res)
        let product = res.data.data
        // 处理商品详细数据
        let infos = []
        if (product.info.length > 0){
          if (product.info[0].info.includes(',')){
            infos = JSON.parse(product.info[0].info).split(',')
          }else {
            infos = JSON.parse(product.info[0].info).split('，')
          }
          
          product.infos = infos
          product.imgs = JSON.parse(product.info[0].imgs)
    
          if (product.info[0].hasOwnProperty('edition')){
            product.edition = JSON.parse(product.info[0].edition)
          }else {
            product.edition = false
          }
        } 
        this.setData({
            product
        })
        this.detailSelect()
      }
    })
  },
    // 购物车默认选择
  detailSelect: function(e){
    let obj = this.data.product.edition.SKU[0]
    let shopType = obj.title.split('+')
    let sku = {
      sku: shopType[0],
      pic: shopType[1]
    }
    let price = obj.price
    sku.price = price
    let totalPrice = price * this.data.shopNum
    totalPrice = totalPrice.toFixed(2)
    this.setData({
      totalPrice,
      sku,
      price
    })
  },

  onLoad: function (options) {
    let shopId = wx.getStorageSync('shopId');
    this.getDetail(shopId);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    wx.request({
      url: 'http://api_dev.wanxikeji.cn/api/shoppingCarList',
      method: 'POST',
      data: {
        token: wx.getStorageSync('token'),
      },
      success:res=>{
        let nu = 0;
        res.data.data.data.forEach(v=>{
          if(v.good_id == this.data.product.good_id){
            nu++;
            return nu;
          }
        })
        this.setData({
          nn:wx.getStorageSync('cartLen')
        })
      }
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})